<template>
    <div class="permission-management">
        <cardBox class="left-wrapper" title="角色列表" icon="&#xe613;">
            <div class="role-list">
                <div v-for="item in roleList" :key="item.roleId" 
                    class="role-item" 
                    :class="{ 'active': currentRoleID == item.roleId }"
                    @click="handleSelectRole(item.roleId)">
                    <div class="role-info">
                        <i class="iconfont">&#xe624;</i> 
                        <span class="role-name">{{ item.roleName }}</span>
                    </div>
                </div>
            </div>
        </cardBox>
        <cardBox class="right-wrapper" title="用户分配" icon="&#xe6f2;">
            <template #right>
                <el-button 
                    size="small" 
                    @click="handleSelectAll" 
                    :disabled="authorityList.length === 0"
                    class="select-all-btn"
                >
                    {{ isAllSelected ? '取消全选' : '全选' }}
                </el-button>
                <el-button 
                    v-if="showRoleEdit" 
                    type="primary" 
                    size="small" 
                    @click="handleSaveAuthorityClick" 
                    icon="el-icon-check"
                    :loading="isLoading"
                    class="save-btn"
                >
                    保存设置
                </el-button>
            </template>
            <div class="user-info-section">
                <div class="stats-cards">
                    <div class="stat-card">
                        <div class="stat-label">已选用户</div>
                        <div class="stat-value selected-count">{{ selectAuthortyRole.length }}</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-label">总用户数</div>
                        <div class="stat-value total-count">{{ authorityList.length }}</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-label">选择比例</div>
                        <div class="stat-value ratio">
                            {{ authorityList.length > 0 ? Math.round((selectAuthortyRole.length / authorityList.length) * 100) : 0 }}%
                        </div>
                    </div>
                </div>

                <div class="filter-section">
                    <el-input
                        v-model="userSearch"
                        placeholder="搜索用户..."
                        prefix-icon="el-icon-search"
                        size="medium"
                        clearable
                        class="user-search-input"
                    />
                    <el-select 
                        v-model="genderFilter" 
                        placeholder="性别筛选" 
                        size="medium" 
                        clearable
                        class="gender-filter"
                    >
                        <el-option label="男" value="1"></el-option>
                        <el-option label="女" value="2"></el-option>
                    </el-select>
                </div>
            </div>
            <div class="user-table-container" v-loading="isLoading" element-loading-text="加载中...">
                <el-table 
                    :data="filteredAuthorityList" 
                    stripe 
                    @selection-change="handleSelectionChangeRole"
                    height="calc(100vh - 460px)"
                    ref="authoritySelectionRole"
                >
                    <el-table-column type="selection" width="55" align="center"></el-table-column>
                    <el-table-column align="center" label="姓名" prop="name"> </el-table-column>
                    <el-table-column align="center" label="性别" prop="gender" width="90">
                        <template slot-scope="scope">
                            <el-tag 
                                v-if="scope.row.gender == 1" 
                                size="small" 
                                effect="plain"
                                class="gender-tag male"
                            >男</el-tag>
                            <el-tag 
                                v-else-if="scope.row.gender == 2" 
                                type="success" 
                                size="small" 
                                effect="plain"
                                class="gender-tag female"
                            >女</el-tag>
                            <span v-else class="gender-empty">-</span>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="工号" prop="employeeNo" ></el-table-column>
                    <el-table-column align="center" label="电话号码" prop="phoneNo" ></el-table-column>
                    <el-table-column align="center" label="备注" prop="remark" show-overflow-tooltip></el-table-column>
                </el-table>
            </div>
        </cardBox>
        <!-- 角色编辑对话框 -->
        <el-dialog
            title="编辑角色"
            :visible.sync="roleDialogVisible"
            width="500px"
            :close-on-click-modal="false"
            class="role-edit-dialog"
        >
            <el-form :model="roleForm" label-width="80px">
                <el-form-item label="角色名称">
                    <el-input 
                        v-model="roleForm.roleName" 
                        placeholder="请输入角色名称"
                        class="role-input"
                    ></el-input>
                </el-form-item>
                <el-form-item label="角色描述">
                    <el-input 
                        type="textarea" 
                        v-model="roleForm.description" 
                        placeholder="请输入角色描述"
                        :rows="4"
                        class="role-textarea"
                    ></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="roleDialogVisible = false" class="cancel-btn">取 消</el-button>
                <el-button type="primary" @click="handleSaveRole" class="confirm-btn">确 定</el-button>
            </span>
        </el-dialog>
    </div>    
</template>

<script>
import {roleList,getUserByRoleId,setRoleUsers} from '@/api/https'
import cardBox from "@/components/base/cardBox.vue";
export default({
    components:{cardBox},
    props:{
         showRoleEdit:{
            type:Number,
            default:0
        }
    },
    data() {
        return {
            roleList:[],
            currentRoleID:'',
            authorityList:[],
            companyId:'',
            selectAuthortyRole:[],
            isLoading:false,
            roleSearch: '',
            userSearch: '',
            genderFilter: '',
            roleDialogVisible: false,
            roleForm: {
                roleId: '',
                roleName: '',
                description: ''
            }
        }
    },
    computed: {
        // 当前选中的角色对象
        currentRole() {
            return this.roleList.find(item => item.roleId === this.currentRoleID) || null;
        },
        // 过滤后的用户列表
        filteredAuthorityList() {
            let result = this.authorityList;
            
            // 按姓名搜索
            if (this.userSearch) {
                result = result.filter(item => 
                    item.name && item.name.toLowerCase().includes(this.userSearch.toLowerCase())
                );
            }
            
            // 按性别筛选
            if (this.genderFilter) {
                result = result.filter(item => 
                    String(item.gender) === this.genderFilter
                );
            }
            
            return result;
        },
        
        // 是否全选
        isAllSelected() {
            return this.selectAuthortyRole.length === this.authorityList.length && this.authorityList.length > 0;
        },
    },
    mounted(){
        this.getRoleMenuList();
    },
    methods:{
        getRoleMenuList(){
            this.isLoading = true;
            roleList().then(res=>{
                this.isLoading = false;
                if(res.isSuccess && res.data && res.data.length > 0){
                    // 添加用户数量统计
                    this.roleList = res.data.map(role => ({
                        ...role,
                        userCount: 0 // 实际项目中可以从接口获取
                    }));
                    this.currentRoleID = res.data[0].roleId;
                    this.onGetUserlList();
                }else{
                    this.roleList = [];
                }
            }).catch(() => {
                this.isLoading = false;
                this.$message.error('获取角色列表失败');
            });
        },
        handleSelectRole(val){
            this.currentRoleID = val;
            this.onGetUserlList();
        },
        onGetUserlList(){
            this.isLoading = true;
            getUserByRoleId({
                RoleID:this.currentRoleID,
                MenuOrgID:this.companyId
            }).then(res=>{
                this.isLoading = false;
                if(res.isSuccess && res.data && res.data.length > 0){
                    this.authorityList = res.data;
                    
                    // 清除之前的选择
                    this.$nextTick(() => {
                        this.$refs.authoritySelectionRole.clearSelection();
                        
                        // 选中已属于该角色的用户
                        res.data.forEach(item => {
                            if(item.thisRole == 1){
                                this.$refs.authoritySelectionRole.toggleRowSelection(item, true);
                            }
                        });
                    });
                }else{
                    this.authorityList = [];
                }
            }).catch(() => {
                this.isLoading = false;
                this.$message.error('获取用户列表失败');
            });
        },
        handleSelectionChangeRole(selection){
            this.selectAuthortyRole = selection;
        },
        handleSaveAuthorityClick(){
            if(this.selectAuthortyRole.length === 0){
                this.$message.warning('请至少选择一个用户');
                return;
            }
            
            this.$confirm(`确定要将选中的 ${this.selectAuthortyRole.length} 个用户分配给 ${this.currentRole.roleName} 角色吗？`, '确认分配', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.isLoading = true;
                const uids = this.selectAuthortyRole.map(item => item.id);
                
                setRoleUsers({
                    roleId: this.currentRoleID,
                    uids: uids
                }).then(res => {
                    this.isLoading = false;
                    if(res.isSuccess){
                        this.$message.success('保存成功！');
                        this.onGetUserlList();
                    }else{
                        this.$message.error(res.errorMessage || '保存失败');
                    }
                }).catch(() => {
                    this.isLoading = false;
                    this.$message.error('保存失败');
                });
            });
        },
        
        handleSaveRole() {
            if (!this.roleForm.roleName) {
                this.$message.warning('请输入角色名称');
                return;
            }
            
            
            this.$message.success('保存成功');
            this.roleDialogVisible = false;
            
            const index = this.roleList.findIndex(item => item.roleId === this.roleForm.roleId);
            if (index !== -1) {
                this.roleList.splice(index, 1, {...this.roleList[index], ...this.roleForm});
            }
        },
        
        handleSelectAll() {
            if (this.isAllSelected) {
                this.$refs.authoritySelectionRole.clearSelection();
            } else {
                this.filteredAuthorityList.forEach(row => {
                    this.$refs.authoritySelectionRole.toggleRowSelection(row, true);
                });
            }
        },
    }
})
</script>

<style scoped lang="scss">
.permission-management {
    margin-top:10px;
    height:calc(100vh - 180px);
    display: grid;
    grid-template-columns: 340px 1fr;

       .role-list {
        flex: 1;
        padding: 12px;
        overflow-y: auto;
        
        .role-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 18px 16px;
            margin-bottom: 8px;
            border-radius: 6px;
            border: 1px solid #e4e7ed;
            transition: all 0.3s ease;
            cursor: pointer;
            
            &:hover {
                background-color: #f5f7fa;
                border-color: #c0c4cc;
            }
            
            &.active {
                background-color: #ecf5ff;
                border-color: #409eff;
                .role-name {
                    font-weight: 600;
                    color: #409eff;
                }
                .role-info{
                    i{
                        color: #409eff;
                    }
                }
                
            }
            
            .role-info {
                display: flex;
                align-items: center;
                flex: 1;
                
                .iconfont {
                    margin-right: 8px;
                    color: #909399;
                }
                
                .role-name {
                    font-size: 14px;
                }
            }
        }
    }
    .right-wrapper{
        margin-left: 10px;
    }
                
    .user-info-section {
        padding: 20px 24px;
        border-bottom: 1px solid #f0f2f5;
        
        .stats-cards {
            display: flex;
            gap: 16px;
            margin-bottom: 20px;
            
            .stat-card {
                flex: 1;
                background: #f8f9fa;
                border-radius: 8px;
                padding: 16px;
                text-align: center;
                border: 1px solid #e9ecef;
                
                .stat-label {
                    font-size: 12px;
                    color: #6c757d;
                    margin-bottom: 8px;
                }
                
                .stat-value {
                    font-size: 24px;
                    font-weight: 700;
                    
                    &.selected-count {
                        color: #409EFF;
                    }
                    
                    &.total-count {
                        color: #67C23A;
                    }
                    
                    &.ratio {
                        color: #E6A23C;
                    }
                }
            }
        }
                    
        .filter-section {
            display: flex;
            gap: 12px;
            
            .user-search-input {
                width: 240px;
                
                ::v-deep .el-input__inner {
                    border-radius: 8px;
                    border: 1px solid #dcdfe6;
                    transition: all 0.3s;
                    
                    &:focus {
                        border-color: #409EFF;
                        box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
                    }
                }
            }
            
            .gender-filter {
                width: 120px;
                
                ::v-deep .el-input__inner {
                    border-radius: 8px;
                }
            }
        }
    }
                
    .user-table-container {
        flex: 1;
        padding: 0 24px 24px;
        
        .user-table {
            border-radius: 8px;
            overflow: hidden;
            
            ::v-deep .el-table__header {
                th {
                    background: #f8f9fa;
                    color: #2c3e50;
                    font-weight: 600;
                }
            }
            
            .user-name-cell {
                display: flex;
                align-items: center;
                justify-content: center;
                
                .name-text {
                    font-weight: 500;
                }
                
                .current-role-badge {
                    margin-left: 6px;
                    color: #67C23A;
                    font-size: 16px;
                }
            }
            
            .gender-tag {
                border: none;
                font-weight: 500;
                
                &.male {
                    background: #ecf5ff;
                    color: #409EFF;
                }
                
                &.female {
                    background: #f0f9ff;
                    color: #67C23A;
                }
            }
            
            .gender-empty {
                color: #909399;
            }
            
            .detail-btn {
                color: #409EFF;
                font-weight: 500;
                
                &:hover {
                    color: #337ecc;
                }
            }
        }
    }
    

}

// 角色编辑对话框样式
.role-edit-dialog {
    ::v-deep .el-dialog {
        border-radius: 12px;
        overflow: hidden;
        
        .el-dialog__header {
            background: linear-gradient(135deg, #fafbfc 0%, #ffffff 100%);
            border-bottom: 1px solid #f0f2f5;
            padding: 20px 24px;
            
            .el-dialog__title {
                font-weight: 600;
                color: #2c3e50;
            }
        }
        
        .el-dialog__body {
            padding: 24px;
            
            .role-input, .role-textarea {
                ::v-deep .el-input__inner,
                ::v-deep .el-textarea__inner {
                    border-radius: 8px;
                    border: 1px solid #dcdfe6;
                    transition: all 0.3s;
                    
                    &:focus {
                        border-color: #409EFF;
                        box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
                    }
                }
            }
        }
        
        .dialog-footer {
            .cancel-btn {
                border-radius: 8px;
                border-color: #dcdfe6;
                
                &:hover {
                    border-color: #409EFF;
                    color: #409EFF;
                }
            }
            
            .confirm-btn {
                background: linear-gradient(135deg, #409EFF 0%, #337ecc 100%);
                border: none;
                border-radius: 8px;
                font-weight: 500;
                
                &:hover {
                    transform: translateY(-1px);
                    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
                }
            }
        }
    }
}
</style>